<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑拍卖商品</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #fff9e6;
            margin: 0;
            padding: 20px;
        }

        .publish-form {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        h2 {
            color: #8b4513;
            text-align: center;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 20px;
            width: 100%;
        }

        .input-with-icon {
            position: relative;
            display: flex;
            align-items: center;
        }

        .input-with-icon i {
            position: absolute;
            left: 12px;
            color: #ffd700;
            font-size: 16px;
        }

        input[type="text"],
        input[type="number"],
        input[type="datetime-local"],
        .location-select,
        .category-select,
        .condition-select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #ffd700;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
            box-sizing: border-box;
        }

        .input-with-icon input {
            padding-left: 35px;
        }

        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #ffb700;
            box-shadow: 0 0 5px rgba(255,183,0,0.3);
        }

        .price-group {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }

        .time-group {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }

        .location-group {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }

        .location-select,
        .category-select,
        .condition-select {
            padding: 10px 12px;
            background-color: white;
            cursor: pointer;
        }

        .location-select:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
            border-color: #ddd;
        }

        textarea {
            height: 150px;
            min-height: 120px;
            resize: vertical;
            font-family: Arial, sans-serif;
        }

        .upload-section {
            width: 100%;
            margin: 20px 0;
            padding: 20px;
            border: 2px solid #ffd700;
            border-radius: 6px;
            text-align: center;
            box-sizing: border-box;
            background-color: white;
        }

        .upload-section:hover {
            background-color: #fff9e6;
            border-color: #ffb700;
            transition: all 0.3s ease;
        }

        .upload-icon {
            font-size: 30px;
            color: #ffd700;
            margin-bottom: 10px;
            transition: color 0.3s ease;
        }

        .upload-section:hover .upload-icon {
            color: #ffb700;
        }

        .upload-section p {
            margin: 10px 0;
            color: #666;
            font-size: 14px;
        }

        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
            padding: 10px;
        }

        .preview-item {
            position: relative;
            width: 100px;
            height: 100px;
            border: 2px solid #ffd700;
            border-radius: 6px;
            overflow: hidden;
            margin: 0;
            flex-shrink: 0;
            background-color: #fff;
            animation: fadeIn 0.3s ease;
        }

        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .cover-badge {
            position: absolute;
            top: 5px;
            left: 5px;
            background-color: #ffd700;
            color: #8b4513;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 13px;
            font-weight: bold;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            text-shadow: 0 1px 1px rgba(255,255,255,0.5);
            border: 1px solid #ffb700;
            animation: glowing 2s infinite;
        }

        @keyframes glowing {
            0% { box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
            50% { box-shadow: 0 2px 8px rgba(255,215,0,0.6); }
            100% { box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
        }

        .set-cover {
            position: absolute;
            bottom: 5px;
            left: 5px;
            background-color: rgba(255, 215, 0, 0.8);
            color: #8b4513;
            border: none;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            z-index: 1;
            transition: opacity 0.3s ease;
        }

        .set-cover:hover {
            opacity: 0;
        }

        .remove-image {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2;
        }

        .remove-image:hover {
            background: #ff6666;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        button {
            width: 100%;
            padding: 15px;
            background-color: #ffd700;
            color: #8b4513;
            border: none;
            border-radius: 6px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }

        button:hover {
            background-color: #ffb700;
            transform: translateY(-2px);
        }

        .back-btn {
            width: auto;
            padding: 8px 15px;
            margin-bottom: 20px;
            background-color: transparent;
            color: #8b4513;
            border: 2px solid #ffd700;
        }

        .back-btn:hover {
            background-color: #fff9e6;
            transform: none;
        }
    </style>
</head>
<body>
    <div class="publish-form">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i> 返回
        </button>
        
        <h2><i class="fas fa-gavel"></i> 编辑拍卖商品</h2>
        
        <div class="form-group">
            <div class="input-with-icon">
                <i class="fas fa-tag"></i>
                <input type="text" id="productName" placeholder="商品名称（必填）">
            </div>
        </div>
        
        <div class="price-group">
            <div class="input-with-icon">
                <i class="fas fa-dollar-sign"></i>
                <input type="number" id="startPrice" placeholder="起拍价" step="0.01">
            </div>
            <div class="input-with-icon">
                <i class="fas fa-tag"></i>
                <input type="number" id="originalPrice" placeholder="原价" step="0.01">
            </div>
            <div class="input-with-icon">
                <i class="fas fa-plus"></i>
                <input type="number" id="minIncrement" placeholder="最小加价" step="1" min="1">
            </div>
        </div>

        <div class="form-group">
            <div class="input-with-icon">
                <i class="fas fa-truck"></i>
                <input type="number" id="shippingFee" placeholder="运费" step="0.01">
            </div>
        </div>

        <div class="time-group">
            <div class="form-group">
                <label><i class="far fa-clock"></i> 开始时间</label>
                <input type="datetime-local" id="startTime" required>
            </div>
            <div class="form-group">
                <label><i class="fas fa-clock"></i> 结束时间</label>
                <input type="datetime-local" id="endTime" required>
            </div>
        </div>

        <div class="form-group">
            <div class="input-with-icon">
                <i class="fas fa-box"></i>
                <input type="text" id="brand" placeholder="品牌名称（必填）">
            </div>
        </div>

        <div class="form-group location-group">
            <select class="location-select" id="province" onchange="loadCities()">
                <option value="">选择省份</option>
            </select>
            <select class="location-select" id="city" onchange="loadDistricts()" disabled>
                <option value="">选择城市</option>
            </select>
            <select class="location-select" id="district" disabled>
                <option value="">选择区县</option>
            </select>
        </div>

        <div class="form-group">
            <select class="category-select" id="productCategory">
                <option value="">选择分类（必选）</option>
                <option value="1">电子产品</option>
                <option value="2">图书教材</option>
                <option value="3">服装饰品</option>
                <option value="4">运动器材</option>
                <option value="5">其他</option>
            </select>
        </div>

        <div class="form-group">
            <select class="condition-select" id="conditionLevel">
                <option value="">选择物品新旧程度（必选）</option>
                <option value="5">全新</option>
                <option value="4">几乎全新</option>
                <option value="3">轻微使用</option>
                <option value="2">明显使用</option>
                <option value="1">重度使用</option>
            </select>
        </div>

        <div class="form-group">
            <textarea id="productDetails" placeholder="商品详情描述（必填）&#13;&#10;建议包含以下信息：&#13;&#10;1. 物品使用时长&#13;&#10;2. 具体使用情况&#13;&#10;3. 是否有损坏&#13;&#10;4. 交易方式"></textarea>
        </div>

        <div class="upload-section" onclick="document.getElementById('imageUpload').click()">
            <input type="file" id="imageUpload" hidden multiple accept="image/*">
            <i class="fas fa-cloud-upload-alt upload-icon"></i>
            <p>点击上传商品图片（最多6张）</p>
            <div class="image-preview" id="imagePreview"></div>
        </div>

        <button onclick="updateAuction()">
            <i class="fas fa-save"></i>
            保存修改
        </button>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        let productId = null;
        let imageUrls = [];

        // 页面加载时获取商品信息
        $(document).ready(function() {
            const urlParams = new URLSearchParams(window.location.search);
            productId = urlParams.get('id');
            
            if (productId) {
                loadProductInfo(productId);
            }
            
            initAreaSelect();
        });

        // 加载商品信息
        function loadProductInfo(id) {
            $.ajax({
                url: `/auction/${id}`,
                type: 'GET',
                success: function(response) {
                    console.log(response);
                    if (response.state === 1) {
                        const product = response.data;
                        
                        // 填充基本信息
                        $('#productName').val(product.productName);
                        $('#startPrice').val(product.startPrice);
                        $('#originalPrice').val(product.originalPrice || '');
                        $('#shippingFee').val(0); // 暂时默认为0
                        $('#brand').val(product.brand);
                        $('#productCategory').val(1); // 暂时默认为1
                        $('#conditionLevel').val(5); // 暂时默认为5
                        $('#productDetails').val(product.productDescription);
                        
                        // 填充拍卖信息，时间提前8小时
                        const adjustTime = (timeStr) => {
                            if (!timeStr) return '';
                            const time = new Date(timeStr);
                            time.setHours(time.getHours() - 8);
                            return time.toISOString().slice(0, 16);
                        };
                        
                        $('#startTime').val(adjustTime(product.startTime));
                        $('#endTime').val(adjustTime(product.endTime));
                        
                        // 设置地址
                        if (product.location) {
                            const location = JSON.parse(product.location);
                            $('#province').val(location.province);
                            loadCities();
                            $('#city').val(location.city);
                            loadDistricts();
                            $('#district').val(location.district);
                        }
                        
                        // 显示图片
                        try {
                            const images = JSON.parse(product.productImage);
                            imageUrls = images;
                            displayImages(imageUrls);
                        } catch (e) {
                            console.error('解析商品图片失败:', e);
                        }
                    } else {
                        alert('加载商品信息失败：' + response.msg);
                    }
                },
                error: function() {
                    alert('加载商品信息失败，请重试');
                }
            });
        }

        // 图片上传预览
        $('#imageUpload').change(function() {
            const files = this.files;
            if (files.length + imageUrls.length > 6) {
                alert('最多只能上传6张图片');
                return;
            }
            
            Array.from(files).forEach(file => {
                const formData = new FormData();
                formData.append('file', file);
                
                $.ajax({
                    url: '/upload/image',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.state === 1) {
                            imageUrls.push(response.data);
                            displayImages(imageUrls);
                        } else {
                            alert('图片上传失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('图片上传失败，请稍后重试');
                    }
                });
            });
        });

        // 显示图片预览
        function displayImages(urls) {
            const preview = $('#imagePreview');
            preview.empty();
            
            urls.forEach((url, index) => {
                preview.append(`
                    <div class="preview-item">
                        <img src="${url}" alt="商品图片">
                        <button type="button" class="remove-image" onclick="removeImage(${index}, event)">
                            <i class="fas fa-times"></i>
                        </button>
                        ${index === 0 ? '<div class="cover-badge">封面</div>' : 
                        `<button type="button" class="set-cover" onclick="setCover(${index}, event)">
                            <i class="fas fa-star"></i> 设为封面
                        </button>`}
                    </div>
                `);
            });
        }

        // 设置封面图片
        function setCover(index, event) {
            event.stopPropagation();
            if (index === 0) return;
            const image = imageUrls.splice(index, 1)[0];
            imageUrls.unshift(image);
            displayImages(imageUrls);
        }

        // 删除图片
        function removeImage(index, event) {
            event.stopPropagation();
            imageUrls.splice(index, 1);
            displayImages(imageUrls);
        }

        // 地区数据
        const areaData = {
            provinces: ['北京市', '上海市', '广东省', '浙江省', '江苏省', '四川省', '湖北省', '河南省'],
            cities: {
                '北京市': ['北京市'],
                '上海市': ['上海市'],
                '广东省': ['广州市', '深圳市', '珠海市', '佛山市', '东莞市', '惠州市'],
                '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '绍兴市'],
                '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '南通市'],
                '四川省': ['成都市', '绵阳市', '德阳市', '宜宾市', '泸州市'],
                '湖北省': ['武汉市', '宜昌市', '襄阳市', '荆州市', '黄石市'],
                '河南省': ['郑州市', '洛阳市', '开封市', '新乡市', '许昌市']
            },
            districts: {
                '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区', '通州区', '昌平区'],
                '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '浦东新区', '闵行区'],
                '广州市': ['越秀区', '海珠区', '荔湾区', '天河区', '白云区', '黄埔区', '番禺区'],
                '深圳市': ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区', '龙华区', '盐田区'],
                '杭州市': ['上城区', '下城区', '江干区', '拱墅区', '西湖区', '滨江区', '萧山区'],
                '宁波市': ['海曙区', '江北区', '北仑区', '镇海区', '鄞州区', '奉化区'],
                '南京市': ['玄武区', '秦淮区', '建邺区', '鼓楼区', '浦口区', '栖霞区'],
                '苏州市': ['姑苏区', '虎丘区', '吴中区', '相城区', '吴江区'],
                '成都市': ['锦江区', '青羊区', '金牛区', '武侯区', '成华区', '高新区'],
                '武汉市': ['江岸区', '江汉区', '硚口区', '汉阳区', '武昌区', '洪山区'],
                '郑州市': ['中原区', '二七区', '管城区', '金水区', '上街区', '惠济区']
            }
        };

        // 初始化地区选择
        function initAreaSelect() {
            const provinceSelect = $('#province');
            provinceSelect.html('<option value="">选择省份</option>');
            areaData.provinces.forEach(province => {
                provinceSelect.append(`<option value="${province}">${province}</option>`);
            });
        }

        // 加载城市
        function loadCities() {
            const province = $('#province').val();
            const citySelect = $('#city');
            const districtSelect = $('#district');
            
            citySelect.html('<option value="">选择城市</option>');
            districtSelect.html('<option value="">选择区县</option>');
            
            if (!province) {
                citySelect.prop('disabled', true);
                districtSelect.prop('disabled', true);
                return;
            }

            citySelect.prop('disabled', false);
            districtSelect.prop('disabled', true);

            const cities = areaData.cities[province] || [];
            cities.forEach(city => {
                citySelect.append(`<option value="${city}">${city}</option>`);
            });
        }

        // 加载区县
        function loadDistricts() {
            const city = $('#city').val();
            const districtSelect = $('#district');
            
            districtSelect.html('<option value="">选择区县</option>');
            
            if (!city) {
                districtSelect.prop('disabled', true);
                return;
            }

            districtSelect.prop('disabled', false);

            const districts = areaData.districts[city] || [];
            districts.forEach(district => {
                districtSelect.append(`<option value="${district}">${district}</option>`);
            });
        }

        // 验证数据
        function validateAuctionData(data) {
            const errors = [];

            if (!data.productName) {
                errors.push('• 商品名称未填写');
            }
            if (!data.startPrice || parseFloat(data.startPrice) <= 0) {
                errors.push('• 起拍价无效，请输入大于0的数字');
            }
            if (!data.minIncrement || parseInt(data.minIncrement) < 1) {
                errors.push('• 最小加价幅度无效，请输入大于等于1的整数');
            }
            if (!data.brand) {
                errors.push('• 品牌名称未填写');
            }

            // 时间验证
            if (!data.startTime || !data.endTime) {
                errors.push('• 拍卖时间未设置完整');
            } else {
                const startTime = new Date(data.startTime);
                const endTime = new Date(data.endTime);
                if (startTime >= endTime) {
                    errors.push('• 结束时间必须晚于开始时间');
                }
            }

            // 地区验证
            try {
                const location = JSON.parse(data.location);
                if (!location.province || !location.city || !location.district) {
                    errors.push('• 地区信息未选择完整');
                }
            } catch (e) {
                errors.push('• 地区信息格式错误');
            }

            if (!data.productDescription) {
                errors.push('• 商品描述未填写');
            }
            if (!data.productImage || JSON.parse(data.productImage).length === 0) {
                errors.push('• 请至少上传一张商品图片');
            }

            return errors;
        }

        // 更新拍卖商品
        function updateAuction() {
            const location = {
                province: $('#province').val(),
                city: $('#city').val(),
                district: $('#district').val()
            };

            // 格式化日期时间，时间加回8小时
            const formatDateTime = (dateTimeStr) => {
                if (!dateTimeStr) return null;
                const dt = new Date(dateTimeStr);
                dt.setHours(dt.getHours() + 8);
                return dt.toISOString();
            };

            const auctionData = {
                id: productId,
                productName: $('#productName').val().trim(),
                startPrice: $('#startPrice').val(),
                originalPrice: $('#originalPrice').val() || null,
                brand: $('#brand').val().trim(),
                productDescription: $('#productDetails').val().trim(),
                location: JSON.stringify(location),
                productImage: JSON.stringify(imageUrls),
                minIncrement: $('#minIncrement').val(),
                startTime: formatDateTime($('#startTime').val()),
                endTime: formatDateTime($('#endTime').val())
            };

            const errors = validateAuctionData(auctionData);
            if (errors.length > 0) {
                alert('请完善以下信息：\n' + errors.join('\n'));
                return;
            }

            $.ajax({
                url: '/seller/product/auction/update',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(auctionData),
                success: function(response) {
                    if (response.state === 1) {
                        alert('修改成功！');
                        window.location.href = 'product-manage.html';
                    } else {
                        alert('修改失败：' + response.msg);
                    }
                },
                error: function(xhr) {
                    console.error('修改失败:', xhr.responseText);
                    alert('修改失败，请稍后重试');
                }
            });
        }
    </script>
</body>
</html> 